<template>
  <div class="code-generation">
    <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleClick">
      <el-tab-pane label="数据源配置" name="datasource">
        <el-card
          class="!border-none mt-4"
          shadow="never"
          v-loading="sourcePager.loading"
        >
          <div class="flex">
            <el-button type="primary" @click="visible = true">
              <template #icon>
                <icon name="el-icon-Plus" />
              </template>
              新增数据源
            </el-button>
          </div>
          <div class="mt-4">
            <el-table
              :data="sourcePager.lists"
              size="large"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column
                label="名称"
                prop="dataSourceName"
                min-width="180"
              />
              <!-- <el-table-column
                label="driverName"
                prop="driverName"
                min-width="180"
              /> -->
              <el-table-column
                label="链接"
                prop="jdbcUrl"
                min-width="180"
                show-overflow-tooltip
              />
              <el-table-column label="用户名" prop="userName" min-width="180" />
              <el-table-column label="密码" prop="pwd" min-width="180" />
              <el-table-column label="操作" width="160" fixed="right">
                <template #default="{ row }">
                  <div class="flex items-center">
                    <el-button type="primary" @click="openDataSource(row)">
                      编辑
                    </el-button>
                    <el-button type="danger" @click="deleteSource(row.id)">
                      删除
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="flex justify-end mt-4">
            <pagination v-model="sourcePager" @change="getSourceLists" />
          </div>
        </el-card>
        <!-- 添加/修改弹框 -->
        <el-dialog
          v-model="visible"
          width="600px"
          :append-to-body="true"
          :before-close="handleClose"
          :title="sourceFormData?.id ? '修改数据源' : '新增数据源'"
        >
          <el-form
            class="ls-form"
            ref="formRef"
            :rules="rules"
            :model="sourceFormData"
            label-width="84px"
          >
            <el-form-item label="编号" prop="id" style="display: none">
              <el-input
                v-model="sourceFormData.id"
                placeholder="id"
                clearable
              />
            </el-form-item>
            <el-form-item label="数据源名称" prop="dataSourceName">
              <el-input
                v-model="sourceFormData.dataSourceName"
                placeholder="数据源名称"
                clearable
              />
            </el-form-item>
            <el-form-item label="用户名" prop="userName">
              <el-input
                v-model="sourceFormData.userName"
                placeholder="请输入用户名"
                clearable
              />
            </el-form-item>
            <el-form-item label="密码" prop="pwd">
              <el-input
                v-model="sourceFormData.pwd"
                placeholder="请输入密码"
                clearable
              />
            </el-form-item>
            <el-form-item label="url" prop="jdbcUrl">
              <el-input
                v-model="sourceFormData.jdbcUrl"
                placeholder="请输入链接"
                clearable
              />
            </el-form-item>
            <el-form-item label="备注" prop="remarke">
              <el-input
                v-model="sourceFormData.remarke"
                type="textarea"
                :autosize="{ minRows: 4, maxRows: 6 }"
                clearable
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </el-form>

          <template #footer>
            <span class="dialog-footer">
              <el-button @click="handleClose">取消</el-button>
              <el-button type="primary" @click="submitDatasource">
                确定
              </el-button>
            </span>
          </template>
        </el-dialog>
      </el-tab-pane>
      <el-tab-pane label="代码生成" name="tables">
        <el-card class="!border-none" shadow="never">
          <el-form class="mb-[-16px]" :model="formData" inline>
            <el-form-item label="表名称">
              <el-input
                class="w-[280px]"
                v-model="formData.tableName"
                clearable
                @keyup.enter="resetPage"
              />
            </el-form-item>
            <el-form-item label="表描述">
              <el-input
                class="w-[280px]"
                v-model="formData.tableComment"
                clearable
                @keyup.enter="resetPage"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="resetPage">查询</el-button>
              <el-button @click="resetParams">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card
          class="!border-none mt-4"
          shadow="never"
          v-loading="pager.loading"
        >
          <div class="flex">
            <data-table
              v-perms="['gen:importTable']"
              class="inline-block mr-[10px]"
              :sourceList="sourcePager.lists"
              @success="getLists"
            >
              <el-button type="primary">
                <template #icon>
                  <icon name="el-icon-Plus" />
                </template>
                导入数据表
              </el-button>
            </data-table>
            <el-button
              v-perms="['gen:delTable']"
              :disabled="!selectData.length"
              @click="handleDelete()"
              type="danger"
            >
              <template #icon>
                <icon name="el-icon-Delete" />
              </template>
              删除
            </el-button>
            <el-button
              v-perms="['gen:genCode', 'gen:downloadCode']"
              :disabled="!selectData.length"
              @click="handleGenerate(selectData)"
            >
              生成代码
            </el-button>
          </div>
          <div class="mt-4">
            <el-table
              :data="pager.lists"
              size="large"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column
                label="表名称"
                prop="tableName"
                min-width="180"
              />
              <el-table-column
                label="表描述"
                prop="tableComment"
                min-width="180"
              />
              <el-table-column
                label="创建时间"
                prop="createTime"
                min-width="180"
              />
              <el-table-column
                label="更新时间"
                prop="updateTime"
                min-width="180"
              />
              <el-table-column label="操作" width="160" fixed="right">
                <template #default="{ row }">
                  <div class="flex items-center">
                    <el-button
                      v-perms="['gen:previewCode']"
                      type="primary"
                      link
                      @click="handlePreview(row.tableId)"
                    >
                      预览
                    </el-button>

                    <el-button type="primary" link v-perms="['gen:editTable']">
                      <router-link
                        :to="{
                          path: '/devtool/code/edit',
                          query: {
                            id: row.tableId
                          }
                        }"
                      >
                        编辑
                      </router-link>
                    </el-button>
                    <el-dropdown
                      class="ml-2"
                      @command="handleCommand($event, row)"
                      v-perms="[
                        'gen:genCode',
                        'gen:downloadCode',
                        'gen:syncTable',
                        'gen:delTable'
                      ]"
                    >
                      <el-button type="primary" link>
                        更多
                        <icon name="el-icon-ArrowDown" :size="14" />
                      </el-button>

                      <template #dropdown>
                        <el-dropdown-menu>
                          <div v-perms="['gen:genCode', 'gen:downloadCode']">
                            <el-dropdown-item command="generate">
                              <el-button type="primary" link>
                                生成代码
                              </el-button>
                            </el-dropdown-item>
                          </div>
                          <div v-perms="['gen:delTable']">
                            <el-dropdown-item command="delete">
                              <el-button type="danger" link> 删除 </el-button>
                            </el-dropdown-item>
                          </div>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="flex justify-end mt-4">
            <pagination v-model="pager" @change="getLists" />
          </div>
        </el-card>
        <code-preview ref="codeViewRef" />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script lang="ts" setup>
import type { FormInstance } from "element-plus";
import {
  generateTable,
  generateDelete,
  generatePreview,
  generateCode,
  downloadCode,
  datasourceList,
  addDataSource,
  delDataSource,
  editDataSource
} from "@/api/code";
import { usePaging } from "@/layout/hooks/usePaging";
import DataTable from "./components/data-table.vue";
import CodePreview from "./components/code-preview.vue";
import feedback from "@/utils/feedback";
import { streamFileDownload } from "@/utils/file";
defineOptions({
  name: "devCode"
});

const visible = ref(false);

const activeName = ref("datasource");
const codeViewRef = ref();
//数据源添加表单
const formRef = shallowRef<FormInstance>();
const initSourceFormData = {
  id: null,
  dataSourceName: null,

  driverName: "",
  userName: "",
  pwd: "",
  jdbcUrl: "",
  remarke: ""
};
const sourceFormData = reactive(initSourceFormData);

const rules = {
  dataSourceName: [
    {
      required: true,
      message: "请输入数据源名称",
      trigger: ["blur"]
    }
  ],
  userName: [
    {
      required: true,
      message: "请输入用户名",
      trigger: ["blur"]
    }
  ],
  pwd: [
    {
      required: true,
      message: "请输入密码",
      trigger: ["blur"]
    }
  ],
  jdbcUrl: [
    {
      required: true,
      message: "请输入数据库链接",
      trigger: ["blur"]
    }
  ]
};
const formData = reactive({
  tableName: "",
  tableComment: "",
  storeId: null //数据源id
});

const previewState = reactive({
  show: false,
  loading: false,
  code: {}
});

//数据表
const { pager, getLists, resetParams, resetPage } = usePaging({
  fetchFun: generateTable,
  params: formData
});

//数据源
const {
  pager: sourcePager,
  getLists: getSourceLists,
  resetPage: sourceRestPage
} = usePaging({
  fetchFun: datasourceList,
  size: 100, //查询100条
  page: 1,
  params: {}
});

const selectData = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  console.log("handleSelectionChange", val);

  selectData.value = val;
};

const handleClose = () => {
  console.log("111");

  visible.value = false;
  formRef.value?.resetFields();
  resetDatasourceFormData();
};
const deleteSource = async (id: any) => {
  await feedback.confirm("确定要删除此数据源？");
  await delDataSource([id]);
  feedback.msgSuccess("操作成功");
  getSourceLists();
};

const openDataSource = async (row: Record<any, any>) => {
  console.log("row", row);

  for (const key in sourceFormData) {
    if (row[key] != null && row[key] != undefined) {
      //@ts-ignore
      sourceFormData[key] = row[key];
    }
  }
  visible.value = true;
};

const resetDatasourceFormData = () => {
  Object.keys(sourceFormData).forEach(item => {
    sourceFormData[item] = undefined;
  });
};

//添加 修改数据源
const submitDatasource = async () => {
  await formRef.value?.validate();
  console.log("sourceFormData", sourceFormData);
  console.log("sourceFormData.id != null", sourceFormData.id != null);

  sourceFormData.id != null
    ? await editDataSource(sourceFormData)
    : await addDataSource(sourceFormData);
  feedback.msgSuccess("操作成功");
  visible.value = false;
  formRef.value?.resetFields();
  resetDatasourceFormData();
  getSourceLists();
};

const handleDelete = async (ids?: number[]) => {
  if (!ids) ids = selectData.value.map(({ tableId }) => tableId);
  console.log("ids-->", ids);

  await feedback.confirm("确定要删除？");
  await generateDelete(JSON.stringify(ids));
  feedback.msgSuccess("删除成功");
  getLists();
};

const handlePreview = async (id: number) => {
  const data: any = await generatePreview(id);
  if (data.success) {
    previewState.code = data.data;
    previewState.show = true;
    codeViewRef?.value.openDialog(previewState.code);
  }
};

const handleGenerate = async (selectData: any[]) => {
  console.log("selectData", selectData);

  const downloadTables = getTables(selectData, 0);
  console.log("downloadTables", downloadTables);

  const genTables = getTables(selectData, 1);
  console.log("genTables", genTables);
  if (downloadTables) {
    console.log("file111");
    const file = await downloadCode(downloadTables);
    console.log("file", file);
    streamFileDownload(file, "lonni-cloud-code.zip");
  }
  if (genTables) {
    await generateCode({ tables: genTables });
    feedback.msgSuccess("生成成功");
  }
};

const getTables = (selectData: any[], type: 0 | 1) => {
  return selectData
    .filter(({ genType }) => genType == type)
    .map(({ tableName }) => tableName)
    .join();
};

const handleCommand = (command: any, row: any) => {
  switch (command) {
    case "generate":
      handleGenerate([row]);
      break;
    case "sync":
      handleSync(row.id);
      break;
    case "delete":
      handleDelete([row.id]);
  }
};

const handleClick = (type: any) => {
  console.log("activeName", activeName);
  console.log("type", type);
  console.log("activeName.value ", activeName.value);
  console.log('activeName.value == "tables"', activeName.value == "tables");

  if (activeName.value == "tables") {
    console.log("tables");

    getLists();
  } else {
    getSourceLists();
  }
};

onActivated(() => {
  //   getLists();
  getSourceLists();
});
</script>
